<?php
namespace app\api\controller\cjai;
use app\admin\model\cjai\Aicategory;
use app\admin\model\cjai\Mingganci;
use app\admin\model\cjai\Liaotian;
use app\common\controller\Api;
use app\common\model\User;
use think\Config;

class Index extends Api{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 获取一级分类
     */
    public function cate()
    {
        $list = Aicategory::where(['status' => 'normal', 'pid' => 0, 'type' => 'default'])->order('weigh asc')->select();
        foreach ($list as &$v) {
            if (!empty($v['image'])) {
                $v['image'] = cdnurl($v['image'], true);
            }
        }
        $this->success('获取成功', $list);
    }

    /**
     * 获取二级分类
     * @param int $id 一级分类id
     *
     */
    public function cate2()
    {
        $id = input('id');
        $page = input('page', 1);
        $limit = input('limit', 10);
        $where['status'] = 'normal';
        if ($id) {
            $where['pid'] = $id;
        } else {
            $where['pid'] = ['>', 0];
        }

        $list = Aicategory::where($where)->order('weigh asc')->page($page, $limit)->select();
        foreach ($list as &$v) {
            if (!empty($v['image'])) {
                $v['image'] = cdnurl($v['image'], true);
            }
        }
        $this->success('获取成功', $list);
    }

    /**
     * test
     */
    public function test()
    {

        ini_set('output_buffering', 'off');
        ini_set('implicit_flush', 'on');
        ob_implicit_flush(true);

        $contnet = input('contnet');
        $user_id = input('user_id');
        $dui_id = input('dui_id');
//                if (empty($contnet)) return json_encode(['code' => 0, 'msg' => '请输入内容']);
        $sk = Config::get('site.ai_sks');

        $url = "https://api.openai.com/v1/chat/completions";
        $headers = [
            "Content-Type: application/json",
            "Authorization: Bearer $sk"
        ];


        $jilu = Liaotian::where('user_id', $user_id)->order('id desc')->limit(1)->value('content');
        $jilu2 = Liaotian::where(['dui_id' => $user_id])->order('id desc')->limit(1)->value('content');

        $arr = [];
        if ($dui_id > 0) {
            $cate = Aicategory::get($dui_id);
            if (!empty($cate['ai'])) {
                $arr[] = ["role" => "system", "content" => $cate['ai']];
            }
        }

        if (!empty($jilu)) {
            $arr[] = ["role" => "user", "content" => $jilu];
        }

        if (!empty($jilu2)) {
            $arr[] = ["role" => "assistant", "content" => $jilu2];
        }

        $arr[] = ["role" => "user", "content" => $contnet];

        $data = [
            "model" => "gpt-3.5-turbo",
            "messages" => $arr,
            "temperature" => 0.7,
            'stream' => true
        ];

        header('Content-Type: text/event-stream');
        header('Transfer-Encoding: chunked');
        header('X-Accel-Buffering: no');
// 创建 cURL 句柄
        $ch = curl_init();

// 设置 cURL 选项
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// 设置写入回调函数，以流式方式处理响应
        curl_setopt($ch, CURLOPT_WRITEFUNCTION, function ($ch, $chunk) {
            echo $chunk;
//            echo PHP_EOL;
            ob_flush();
            flush();
            return strlen($chunk);
        });

// 执行请求
        curl_exec($ch);

// 关闭 cURL 句柄
        curl_close($ch);


    }

    /**
     * 发送内容
     * @param string $content 内容
     * @param int $dui_id 对方id
     */
    public function send()
    {
        $content = input('content');
        $dui_id = input('dui_id');

        if (empty($content)) $this->error('内容不能为空');
        $user = User::get($this->auth->id);
        if ($user['group_id'] == 2) {

        } else {
            if ($user['d_time'] < time()) {
                if ($user['cishu'] > 0) {
                    $user->cishu = $user['cishu'] - 1;
                    $user->save();
                } else {
                    $this->error('次数不足，看广告或者充值获得次数吗', [], 100);
                }
            }
        }
        $data = [
            'content' => $content,
            'dui_id' => $dui_id,
            'user_id' => $this->auth->id
        ];
        $res = Liaotian::create($data);

        $data = Mingganci::order('id desc')->select();
        foreach ($data as $k => $v) {
            $ci = explode(',', $v['key']);

            foreach ($ci as $k1 => $v1) {
                if (strpos($content, $v1) !== false) {
                    $this->success('ok', ['content' => $v['content']], 101);
                }
            }
        }


        if ($res) $this->success('发送成功');
        $this->error('发送失败');

    }


    /**
     * 聊天记录
     * @param int $dui_id 对方id
     */
    public function sendHuitiao()
    {
        $content = input('content');
        $dui_id = input('dui_id');
        $data2 = [
            'content' => $content,
            'dui_id' => $this->auth->id,
            'user_id' => $dui_id
        ];
        $bool = Liaotian::create($data2);
        if ($bool) $this->success('保存成功');
        $this->error('保存失败');
    }


    /**
     * 页面加载返回聊天记录
     * @param int $dui_id 对方id
     */
    public function load()
    {
        $user_id = $this->auth->id;
        $dui_id = input('dui_id');

        $limit = input('limit', 10);
        $page = input('page');

        $message = Liaotian::where('(user_id=:user_id and dui_id=:dui_id) || (user_id=:dui_id1 and dui_id=:user_id1)', ['user_id' => $user_id, 'dui_id' => $dui_id, 'dui_id1' => $dui_id, 'user_id1' => $user_id])
            ->order('id desc')
            ->paginate($limit, false, ['page' => $page])->toArray();
        array_multisort(array_column($message['data'], 'id'), SORT_ASC, $message['data']);

        foreach ($message['data'] as &$v) {
            $v['user'] = \app\common\model\User::get($v['user_id']);
            if (!empty($v['user']['avatar'])) {
                $v['user']['avatar'] = 'https://' . $_SERVER['HTTP_HOST'] . $v['user']['avatar'];
            }
//            $v['time'] = date('Y-m-d H:i:s',$v['create_time']);
        }
        $data = [
            'message' => $message
        ];
        $this->success('成功', $data);
    }
}